package com.mdxl.first.Dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.mdxl.first.Dao.db.AbstarctMongoDBConnection;
import com.mdxl.first.exception.ServiceException;
import com.mdxl.first.util.Constant;
import com.mdxl.first.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;

public abstract class AbstractMongoDAO implements IMongoDAO{

	protected static Logger logger = LoggerFactory.getLogger(AbstractMongoDAO.class);
	
	protected DB db;
	protected AbstarctMongoDBConnection dbConnection;
	
	/**
	 * save(新增)
	 * @param model
	 * @param json
	 * @return
	 * @throws Exception
	 *             String
	 * @exception
	 * @since 1.0.0
	 */
	public JSONObject save(String model, String json) throws ServiceException {
		String date = DateUtils.date24ToString(new Date());
		DBObject dbObject = (DBObject) JSON.parse(json);
		
		ObjectId id = null;
		String objectId = dbObject.get(Constant.OBJECTID)==null?null:(String)dbObject.get(Constant.OBJECTID);
		if(StringUtils.isEmpty(objectId)){
			id = ObjectId.get();
			objectId = id.toString();
		}else{
			id = new ObjectId(objectId);
		}
		
		dbObject.put("_id", id);// 系统主键
		dbObject.put(Constant.OBJECTID, objectId);// 业务主键
		dbObject.put(Constant.CREATED_AT, date);
		dbObject.put(Constant.UPDATED_AT, date);
		DBCollection dbCollection = db.getCollection(model);
		dbCollection.insert(dbObject, WriteConcern.SAFE);
		JSONObject returnValue = new JSONObject();
		returnValue.put(Constant.OBJECTID, objectId);// 业务主键
		returnValue.put(Constant.CREATED_AT, date);
		returnValue.put(Constant.UPDATED_AT, date);
		return returnValue;
	}
	
	public JSONObject save(String model, JSONArray list) throws ServiceException {

		String date = DateUtils.date24ToString(new Date());
		List<DBObject> insert_list = new ArrayList<DBObject>();
		for (int i = 0; i < list.size(); i++) {
			DBObject db = (DBObject)JSON.parse(list.getString(i));

			ObjectId id = null;
			String objectId = db.get(Constant.OBJECTID)==null?null:(String)db.get(Constant.OBJECTID);
			if(StringUtils.isEmpty(objectId)){
				id = ObjectId.get();
				objectId = id.toString();
			}else{
				id = new ObjectId(objectId);
			}
			db.put("_id", id);// 系统主键
			db.put(Constant.OBJECTID, objectId);// 业务主键
			db.put(Constant.CREATED_AT, date);
			db.put(Constant.UPDATED_AT, date);
			insert_list.add(db);
		}

		DBCollection dbCollection = db.getCollection(model);
		WriteResult insert = dbCollection.insert(insert_list, WriteConcern.SAFE);
		JSONObject returnValue = new JSONObject();
		returnValue.put("save_count", insert.getN());// 业务主键
		returnValue.put(Constant.CREATED_AT, date);
		returnValue.put(Constant.UPDATED_AT, date);
		return returnValue;
	}
	
	/**
	 * delete(删除)
	 * @param model
	 * @param id
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	public JSONObject delete(String model, String id) throws ServiceException{
		DBCollection dbCollection = db.getCollection(model);
		String date = DateUtils.date24ToString(new Date());
		DBObject dbObject = new BasicDBObject(Constant.OBJECTID, id);
		WriteResult wr = dbCollection.remove(dbObject,WriteConcern.SAFE);
		if(wr.getN()<=0) {
			return null;
		}
		JSONObject returnValue = new JSONObject();
		returnValue.put(Constant.OBJECTID, id);// 业务主键
		returnValue.put(Constant.UPDATED_AT, date);
		return returnValue;
	}

	/**
	 * update(更新)
	 * @param model
	 * @param json
	 * @param id
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	public JSONObject update(String model, String json, String id) throws ServiceException{
		if(StringUtils.isEmpty(id)){
			return null;
		}

		DBCollection dbCollection = db.getCollection(model);
		DBObject updateDBObject = (DBObject) JSON.parse(json);
		String date = DateUtils.date24ToString(new Date());
		updateDBObject.put(Constant.UPDATED_AT, date);
		WriteResult wr = dbCollection.update(new BasicDBObject(Constant.OBJECTID, id), new BasicDBObject("$set", updateDBObject),false,true,WriteConcern.SAFE);
		if(wr.getN()<=0 || !wr.isUpdateOfExisting()) {
			return null;
		}
		JSONObject returnValue = new JSONObject();
		returnValue.put(Constant.OBJECTID, id);// 业务主键
		returnValue.put(Constant.UPDATED_AT, date);
		return returnValue;
	}
	
	public JSONObject updateUnset(String model, String json, String id) {
		if(StringUtils.isEmpty(id)){
			return null;
		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject updateDBObject = (DBObject) JSON.parse(json);
		String date = DateUtils.date24ToString(new Date());
		updateDBObject.put(Constant.UPDATED_AT, date);
		WriteResult wr = dbCollection.update(new BasicDBObject(Constant.OBJECTID, id), new BasicDBObject("$unset", updateDBObject),false,true,WriteConcern.SAFE);
		if(wr.getN()<=0 || !wr.isUpdateOfExisting()) {
			return null;
		}
		JSONObject returnValue = new JSONObject();
		returnValue.put(Constant.OBJECTID, id);// 业务主键
		returnValue.put(Constant.UPDATED_AT, date);
		return returnValue;
	}

//	public JSONObject updateByCondition(String model, String json, String condition) throws ServiceException{
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
//		DBCollection dbCollection = db.getCollection(model);
//		DBObject conditionDBObject = (DBObject) JSON.parse(condition);
//		DBObject updateDBObject = (DBObject) JSON.parse(json);
//		String date = DateUtils.date24ToString(new Date());
//		updateDBObject.put(Constant.UPDATED_AT, date);
//		WriteResult wr = dbCollection.update(conditionDBObject, new BasicDBObject("$set", updateDBObject),false,false,WriteConcern.SAFE);
//		if(wr.getN()<=0 || !wr.isUpdateOfExisting()) {
//			return null;
//		}
//		JSONObject returnValue = new JSONObject();
//		returnValue.put(Constant.UPDATED_AT, date);
//		return returnValue;
//	}
	
//	public JSONObject baseUpdateAndIncByCondition(String model, JSONObject json, String condition) throws ServiceException{
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
//		DBCollection dbCollection = db.getCollection(model);
//		DBObject conditionDBObject = (DBObject) JSON.parse(condition);
//		JSONObject $set = json.getJSONObject("$set");
//		JSONObject $unset = json.getJSONObject("$unset");
//		JSONObject $inc = json.getJSONObject("$inc");
//		DBObject updateDBObject = null == $set ? null : (DBObject) JSON.parse($set.toJSONString());
//		DBObject unsetUpdateDBObject = null == $unset ? null : (DBObject) JSON.parse(JSONObject.toJSONString($unset, SerializerFeature.WriteNullStringAsEmpty ,SerializerFeature.WriteMapNullValue));
//		DBObject incDBObject = null == $inc ? null : (DBObject) JSON.parse($inc.toJSONString());
//		String date = DateUtils.date24ToString(new Date());
//		BasicDBObject basicDBObject = new BasicDBObject();
//		if (null != updateDBObject) {
//			updateDBObject.put(Constant.UPDATED_AT, date);
//			basicDBObject.put("$set", updateDBObject);
//		}
//		if (null != incDBObject) {
//			basicDBObject.put("$inc", incDBObject);
//		}
//		if (null != unsetUpdateDBObject) {
//			basicDBObject.put("$unset", unsetUpdateDBObject);
//		}
//		WriteResult wr = dbCollection.update(conditionDBObject, basicDBObject,false,true,WriteConcern.SAFE);
//		if(wr.getN()<=0 || !wr.isUpdateOfExisting()) {
//			return null;
//		}
//		JSONObject returnValue = new JSONObject();
//		returnValue.put(Constant.UPDATED_AT, date);
//		return returnValue;
//	}

	
	
	/**
	 * 
	 * 查找并更新
	 * findAndModifySet(更新)
	 * 使用时需要注意：
	 * 1.默认使用$set，其中包含$inc的处理
	 * 2.如果需要用到其他的mongodb的语法还需增加判断和处理
	 * 若不想修改次方法；可使用宝哥写的findAndModify；
	 * 从前台将需处理的字段填写好
	 * 
	 * @param model
	 * @param update
	 * @param where
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
//	public JSONObject findAndModifySet(String model, String update, String where) throws ServiceException{
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
//		DBCollection dbCollection = db.getCollection(model);
//		DBObject updateDBObject = (DBObject) JSON.parse(update);
//		DBObject ref = (DBObject) JSON.parse(where);
//		if (ref.containsField(Constant.OBJECTID)&&DataTypeUtils.isNotEmpty(ref.get(Constant.OBJECTID))) {
//			ref.put("_id", new ObjectId(String.valueOf(ref.get(Constant.OBJECTID))));
//			BasicDBObject basicDBObject = new BasicDBObject();
//			if (updateDBObject.containsKey(MongoCondition.INC.getVal())) {
//				basicDBObject.put(MongoCondition.INC.getVal(), updateDBObject.get(MongoCondition.INC.getVal()));
//				updateDBObject.removeField(MongoCondition.INC.getVal());
//			}
//			String date = DateUtils.date24ToString(new Date());
//			updateDBObject.put(Constant.UPDATED_AT, date);
//			basicDBObject.put("$set", updateDBObject);
//			DBObject findAndModify = dbCollection.findAndModify(ref, null, null, false, basicDBObject, true, false);
//			if (findAndModify==null) {
//				return null;
//			}
////			try {
////				cacheService.del(model+":"+findAndModify.get(Constant.OBJECTID));
////			} catch (Exception e) {
////				e.printStackTrace();
////			}
//			return JSONObject.parseObject(findAndModify.toString());
//		}else{
//			throw new ServiceException("where条件必须包含"+Constant.OBJECTID+"字段");
//		}
//	}

	/**
	 * 
	 * inc(自增长)
	 * 
	 * @param model
	 * @param json
	 * @param id
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	public JSONObject inc(String model, String json, String id) throws ServiceException{
		if(StringUtils.isEmpty(id)){
			return null;
		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject updateDBObject = (DBObject) JSON.parse(json);
		BasicDBObject query = new BasicDBObject(Constant.OBJECTID, id);
//		query.put("_id", new ObjectId(id));
		query.put("objectId", id);
		DBObject findAndModify = dbCollection.findAndModify(query, new BasicDBObject("$inc", updateDBObject));
		if (findAndModify==null) {
			return null;
		}
		return JSONObject.parseObject(findAndModify.toString());
	}
	
	/**
	 * 批量自增长
	 * @param model
	 * @param json
	 * @param condition
	 * @return
	 * @throws ServiceException
	 */
	public JSONObject batchInc(String model, String json, JSONObject condition) throws ServiceException{
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject updateDBObject = (DBObject) JSON.parse(json);
		BasicDBObject query = new BasicDBObject(condition);
		WriteResult wr = dbCollection.update(query, new BasicDBObject("$inc", updateDBObject),false,true,WriteConcern.SAFE);
		if(wr.getN()<=0 || !wr.isUpdateOfExisting()) {
			return null;
		}
		JSONObject returnValue = new JSONObject();
		returnValue.put(Constant.UPDATED_AT, 	DateUtils.getTodayYYYYMMDD());
		return returnValue;
	}
	
	/**
	 * 聚合函数
	 * @param model 表
	 * @param query 查询条件
	 * @param sort 排序
	 * @param skip 分页
	 * @param limit 分页
	 * @return
	 * @throws Exception
	 */
	public JSONArray aggregate(String model, String query, String sort, int skip, int limit) throws Exception {
		if(StringUtils.isBlank(model)||StringUtils.isBlank(query)){
			return null;
		}
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		BasicDBObject $query = (BasicDBObject)JSON.parse(query);
		BasicDBObject $skip = new BasicDBObject("$skip", skip);
		BasicDBObject $limit = new BasicDBObject("$limit", limit);
		List<BasicDBObject> list = new ArrayList<BasicDBObject>();
		list.add($query);
		if(StringUtils.isNotBlank(sort)){
			list.add((new BasicDBObject("$sort", (BasicDBObject)JSON.parse(sort))));
		}
		list.add($skip);
		list.add($limit);
		AggregationOutput out = dbCollection.aggregate(list);
		Iterator<DBObject> itor = out.results().iterator();
		JSONArray results = new JSONArray();
		while(itor.hasNext()){
			results.add(JSONObject.parseObject(itor.next().toString()));
		}
		return results;
	}
	/**
	 * 聚合函数
	 * aggregate:
	 * @author sid
	 * @param model
	 * @param conditions
	 * 通过管道操作；具体可用管道如下：
	 * $project：修改输入文档的结构。可以用来重命名、增加或删除域，也可以用于创建计算结果以及嵌套文档。
	 * $match：用于过滤数据，只输出符合条件的文档。$match使用MongoDB的标准查询操作。
	 * $limit：用来限制MongoDB聚合管道返回的文档数。
	 * $skip：在聚合管道中跳过指定数量的文档，并返回余下的文档。
	 * $unwind：将文档中的某一个数组类型字段拆分成多条，每条包含数组中的一个值。
	 * $group：将集合中的文档分组，可用于统计结果。
	 * $sort：将输入文档排序后输出。
	 * $geoNear：输出接近某一地理位置的有序文档。
	 * 下面是表达式内的可以函数
	 * $sum、$avg、$min、$max、$push、$addToSet、$first、$last
	 * @return
	 * @throws Exception
	 */
	public JSONArray aggregate(String model, List<String> conditions) {
		DBCollection dbCollection = db.getCollection(model);
		List<BasicDBObject> list = new ArrayList<BasicDBObject>();
		for (String str : conditions) {
			list.add((BasicDBObject)JSON.parse(str));
		}
		AggregationOutput out = dbCollection.aggregate(list);
		Iterator<DBObject> itor = out.results().iterator();
		JSONArray results = new JSONArray();
		while(itor.hasNext()){
			results.add(JSONObject.parseObject(itor.next().toString()));
		}
		return results;
	}
	/**
	 * 聚合函数
	 * @param model
	 * @param pipeline
	 * @return
	 * @throws Exception
	 */
	public JSONArray aggregate(String model, String pipeline) throws Exception{
		DBCollection table = db.getCollection(model);
		@SuppressWarnings("unchecked")
		List<BasicDBObject> list = (ArrayList<BasicDBObject>) JSON.parse(pipeline);
		AggregationOutput output = table.aggregate(list);
		Iterator<DBObject> itor = output.results().iterator();
		JSONArray results = new JSONArray();
		while(itor.hasNext()){
			//DBObject o = itor.next();
			results.add(JSONObject.parseObject(itor.next().toString()));
		}
		return results;
	}
	
	/**
	 * 
	 * get(按id查找)
	 * 
	 * @param model
	 * @param id
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	public String get(String model, String id) throws ServiceException{
		if(StringUtils.isEmpty(id)){
			return null;
		}
		String cacheString = null;//cacheService.get(model+":"+id);
		if(StringUtils.isBlank(cacheString)){
			DBCollection dbCollection = db.getCollection(model);
			DBObject dbObject = dbCollection.findOne(new BasicDBObject(Constant.OBJECTID, id));
			if(dbObject!=null){
				cacheString = dbObject.toString();
			}
//			if(StringUtils.isNotBlank(cacheString)){
//				try {
//					//cacheService.set(model+":"+id, cacheString);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
		}
		if(StringUtils.isBlank(cacheString)){
			return null;
		}
		return cacheString;
	}

	/**
	 * 
	 * find(高级查询)
	 * @param query
	 *            查询条件
	 * @param fields
	 *            返回字段
	 * @param orderBy
	 *            排序条件
	 * @param model
	 *            查询模型
	 * @param numToSkip
	 *            跳过条数
	 * @param batchSize
	 *            返回条数
	 * @return List<DBObject>
	 * @exception
	 * @since 1.0.0
	 */
	public DBObject find(String where, String fields, String orderBy, String model, int skip, int size) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject ref = (DBObject) JSON.parse(where);
		DBObject keys = (DBObject) JSON.parse(fields);
		keys.put("_id", 0);//不返回系统主键
		DBObject order = (DBObject) JSON.parse(orderBy);
		DBCursor dbCursor = dbCollection.find(ref, keys).sort(order).skip(skip).limit(size);
		BasicDBList list = new BasicDBList();
		DBObject result = new BasicDBObject();
		while (dbCursor.hasNext()) {
			list.add(dbCursor.next());
		}
		result.put("count", dbCursor.count());
		result.put(Constant.RESULTS, list);
		return result;
	}

	/**
	 * 
	 * find(高级查询)
	 * 
	 * @param query
	 *            查询条件
	 * @param fields
	 *            返回字段
	 * @param orderBy
	 *            排序条件
	 * @param model
	 *            查询模型
	 * @return List<DBObject>
	 * @exception
	 * @since 1.0.0
	 */
	@Override
	public DBObject find(String where, String fields, String orderBy, String model) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject ref = (DBObject) JSON.parse(where);
		DBObject keys = (DBObject) JSON.parse(fields);
		keys.put("_id", 0);//不返回系统主键
		DBObject order = (DBObject) JSON.parse(orderBy);
		DBCursor dbCursor = dbCollection.find(ref, keys).sort(order);
		BasicDBList list = new BasicDBList();
		DBObject result = new BasicDBObject();
		while (dbCursor.hasNext()) {
			list.add(dbCursor.next());
		}
		result.put("count", dbCursor.count());
		result.put(Constant.RESULTS, list);
		return result;
	}

	/**
	 * 
	 * distinct(高级查询)
	 * 
	 * @param query
	 *            查询条件
	 * @param fieldName
	 *            指定字段
	 * @param model
	 *            查询模型
	 * @return List<DBObject>
	 * @exception
	 * @since 1.0.0
	 */
	@Override
	public List<?> distinct(String query,String fieldName, String model) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject q = (DBObject) JSON.parse(query);
		List<?> distincts = dbCollection.distinct(fieldName, q);
		return distincts;
	}

	/**
	 * 
	 * eval(在mongo Server上执行js函数)
	 * 
	 * @param function
	 * @param args
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	@Override
	public String eval(String function, String json) {
		// 使用javascript最好是预先定义好注册到数据库服务端，客户端传入函数名及参数即可
		String code = "function(obj){return "+function+"(obj);}";
		DBObject obj = (DBObject) JSON.parse(json);
		Object o = db.eval(code, obj);
		String value = null;
		if(o instanceof Boolean){
			value = String.valueOf(((Boolean)o).booleanValue());
		}else if(o instanceof Number){
			value = String.valueOf((Number)o);
		}else if(o instanceof String){
			value = String.valueOf(o);
		}else if(o instanceof BasicDBObject){
			value = ((BasicDBObject)o).toString();
		}else if(o instanceof BasicDBList){
			value = ((BasicDBList)o).toString();
		}
		return value;
	}
	
	/**
	 * 原子修改操作
	 * @param model
	 * @param where
	 * @param update
	 * @param returnNew true返回修改后数据,false 返回修改前的数据
	 * @param upsert true 修改的记录不存在则新增一条
	 * @return
	 */
	@Override
	public JSONObject findAndModify(String model, String where, String update, boolean returnNew, boolean upsert){
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject query = (DBObject) JSON.parse(where);
		if(query.containsField(Constant.OBJECTID)){
			query.put("_id", new ObjectId(String.valueOf(query.get(Constant.OBJECTID))));
		}
		DBObject updateObject = (DBObject) JSON.parse(update);
		DBObject result = dbCollection.findAndModify(query, null, null, false, updateObject, returnNew, upsert);
		if (result == null) {
			return null;
		}
//		try {
//			cacheService.del(model+":"+result.get(Constant.OBJECTID));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		return JSONObject.parseObject(result.toString());
	}

	/**
	 * 插入
	 * @param model
	 *            集合名
	 * @param obj
	 *            新文档
	 */
	@Override
	public WriteResult insert(String model, DBObject obj) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		return dbCollection.insert(obj);
	}

	/**
	 * 更新
	 * 
	 * @param model
	 *            集合名
	 * @param dbDoc
	 *            更新目标条件
	 * @param newDoc
	 *            新文档
	 * @param insertAllow
	 *            查找无效后是否可插入
	 * @param multiAlter
	 *            是否可以多条更新
	 */
//	public WriteResult update(String model, DBObject dbDoc, DBObject newDoc, boolean insertAllow, boolean multiAlter) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
//		DBCollection dbCollection = db.getCollection(model);
//		return dbCollection.update(dbDoc, newDoc, insertAllow, multiAlter);
//	}

	/**
	 * 查询
	 * @param model
	 *            集合名
	 * @param obj
	 *            条件文档
	 * @return DBCursor 游标
	 */
	@Override
	public DBCursor find(String model, DBObject obj) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		return dbCollection.find(obj);
	}

	/**
	 * 查询unique
	 * 
	 * @param collection
	 *            集合名
	 * @param obj
	 *            条件文档
	 * @return DBObject 文档对象
	 */
	@Override
	public DBObject findOne(String model, DBObject obj) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		return dbCollection.findOne(obj);
	}

	/**
	 * 查询
	 * 
	 * @param model
	 *            集合名
	 * @param key
	 *            查询条件键
	 * @param value
	 *            查询条件值
	 * @return DBCursor 游标
	 */
	@Override
	public DBCursor find(String model, String key, String value) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBObject query = new BasicDBObject();
		query.put(key, value);
		DBCollection dbCollection = db.getCollection(model);
		return dbCollection.find(query);
	}
	
	@Override
	public DBCursor find(String model, String key, Object value) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBObject query = new BasicDBObject();
		query.put(key, value);
		DBCollection dbCollection = db.getCollection(model);
		return dbCollection.find(query);
	}

	/**
	 * 查询unique
	 * 
	 * @param model
	 *            集合名
	 * @param key
	 *            查询条件键
	 * @param value
	 *            查询条件值
	 * @return DBObject 文档对象
	 */
	@Override
	public DBObject findOne(String model, String key, String value) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBObject query = new BasicDBObject();
		query.put(key, value);
		DBCollection dbCollection = db.getCollection(model);
		return dbCollection.findOne(query);
	}
	
	//对集合启动分片，前提是所在数据库已启动分片
	private boolean shardCollection(String dbname,String model,String key){
//		if (dbConnection.isShard()) {
//			logger.info("新的集合"+model+"启动分片");
//			MongoDatabase admin = dbConnection.getMongoClient().getDatabase("admin");
//			BasicDBObject cmd = new BasicDBObject();
//			BasicDBObject shardKeys = new BasicDBObject();
//			shardKeys.put("_id",  1);shardKeys.put(Constant.OBJECTID,  1);
//			cmd.put("shardcollection", dbname+"."+model);
//			cmd.put("key", shardKeys);
//			Document result = admin.runCommand(cmd);
//			logger.info("mongodb cmd:"+cmd);
//			logger.info("document:"+result.toJson());
//			if(result==null||result.isEmpty()){
//				return false;
//			}else if(result.getDouble("ok")>0){
//				return true;
//			}
//		}
		return false;
	}
	
	@Override
	public JSONObject updateByCondition(String model, String json, String condition) {
//		if(!db.collectionExists(model)){
//			shardCollection(KeegooConfig.mongoDBName, model, "_id");
//		}
		DBCollection dbCollection = db.getCollection(model);
		DBObject conditionDBObject = (DBObject) JSON.parse(condition);
		DBObject updateDBObject = (DBObject) JSON.parse(json);
		String date = DateUtils.date24ToString(new Date());
		updateDBObject.put(Constant.UPDATED_AT, date);
		WriteResult wr = dbCollection.update(conditionDBObject, new BasicDBObject("$set", updateDBObject),false,true,WriteConcern.SAFE);
		if(wr.getN()<=0 || !wr.isUpdateOfExisting()) {
			return null;
		}
		JSONObject returnValue = new JSONObject();
		returnValue.put(Constant.UPDATED_AT, date);
		return returnValue;
	}

}
